package org.top10.parser;

import java.util.ArrayList;
import java.util.List;

import org.top10.entity.News;
import org.top10.executor.ParseSource;
import org.top10.util.TOP10Global;
import org.w3c.dom.Node;

public class HuanqiuTask extends Task {

	private static final int webSiteID = TOP10Global.WEB_SITE_ID_HUANGQIU;// 对应网站ID
	private static final String ENCoding = TOP10Global.Encoding_UTF8;// 对应网站ID

	public HuanqiuTask() {
		super(webSiteID, ENCoding);
	}

	public void loadParser() {
		PARSER.add(new NewsParser());
	}

	public static void main(String args[]) throws Exception {
		new NewsParser().dealText(ENCoding);
	}
}

abstract class HuanqiuParser extends TOPParserImpl {
	
	public HuanqiuParser(String c,String url) {
		super(c,TOP10Global.TYPE_News, url);
	}

	public abstract List parse(ParseSource doc) throws Exception;

	public abstract News build(Node node, int rank) throws Exception;

	// XUNlei所有解析器的公有方法放在这里..
}
class NewsParser extends HuanqiuParser{
	private final static String WEBURL="http://www.huanqiu.com/www/188/";
	private final static String SIGN="新闻总排行";
	private final static String TITLE="新闻总排行";
	public NewsParser() {
		super(TITLE,WEBURL);
	}

	public News build(Node a, int rank) throws Exception {
		
		String url = getAttrValueByTag(a, "href");
		if(url.indexOf("com/content_comment")!=-1)return null;
		News v = new News();
		v.setRank(rank);
		v.setLinkUrl(url);
		v.setName(a.getTextContent());
		return v;
	}

	public List parse(ParseSource doc) throws Exception {
		Node body = doc.getDocSource().getElementsByTagName("body").item(0);
		Node node = getNodeByText(body, "h2",SIGN).getParentNode();
		if (node != null) {
			ArrayList<Node> dls = new ArrayList<Node>();
			getAllTagsByParent(node, "a", dls);
			List<News> list = new ArrayList<News>();
			int rank = 1;
			for (Node d : dls) {
				News v = build(d, rank);
				if(v!=null){
					list.add(v);
					System.out.println(v.toString());
					rank++;
					if(rank>10)break;
				}
			}
			return list;
		}
		return null;
	}
}
